<?php

namespace app\api\controller\user;

use app\api\controller\Controller;

use app\api\model\Order as OrderModel;
use app\api\model\Setting as SettingModel;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\service\qrcode\Extract as ExtractQRcode;

use app\common\model\Wxapp as WxappModel;
use app\common\library\wechat\WxSubMsg;
/**
 * 用户订单管理
 * Class Order
 * @package app\api\controller\user
 */
class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 我的订单列表
     * @param $dataType
     * @return array
     * @throws \think\exception\DbException
     */
    public function lists($dataType = '')
    {
        $jiuzhen_id = input()['jiuzhen_id'];
        // $jiuzhen_id = "3";
        // dump($dataType);die;
        $model = new OrderModel;
        $list = $model->getList($this->user['user_id'], $dataType,$jiuzhen_id );
        // dump($list);die;
        for ($i=0; $i < count($list); $i++) { 
            $list[$i]['goods'][0]['jiuzhen'] = DB("user_jiuzhen")->where("jiuzhen_id",$list[$i]['goods'][0]['jiuzhen_id'])->find();
            $list[$i]['goods'][0]['category'] = DB("category")->where("category_id",DB("goods")->where("goods_id",$list[$i]['goods'][0]['goods_id'])->find()['category_id'])->find() ;
            $list[$i]['goods'][0]['jiuzhen_week'] = $this->getDayOfWeek($list[$i]['goods'][0]['jiuzhen_day']);
            $list[$i]['goods'][0]['jiuzhen_period'] = $this->getTimePeriod($list[$i]['goods'][0]['jiuzhen_time']);
            if ($list[$i]['goods'][0]['category']['category_id'] == 10095) {
                $list[$i]['goods'][0]['jiuzhen_day'] = $list[$i]['goods'][0]['jiuzhen_day'] ."/".$list[$i]['goods'][0]['jiuzhen_week']."/".$list[$i]['goods'][0]['jiuzhen_period'];
            }else{
                $list[$i]['goods'][0]['jiuzhen_day'] = $list[$i]['goods'][0]['jiuzhen_day'] ."/".$list[$i]['goods'][0]['jiuzhen_week']."/".$list[$i]['goods'][0]['jiuzhen_period'];
            }
            
            $list[$i]['goods'][0]['mz_type'] = DB("goods")->where("goods_id", $list[$i]['goods'][0]['goods_id'])->find()['mz_type'];
            // 开始判断是否申请售后 
            // $list[$i]['state_text'] = 213121;
            // dump($list[$i]['goods'][0]['jiuzhen_id']);die;
        }
        
        return $this->renderSuccess(compact('list'));
    }
    
    public function getDayOfWeek($date) {
        $weekdays = [
            'Sunday' => '周日',
            'Monday' => '周一',
            'Tuesday' => '周二',
            'Wednesday' => '周三',
            'Thursday' => '周四',
            'Friday' => '周五',
            'Saturday' => '周六',
        ];
    
        $englishDay = date('l', strtotime($date)); // 获取英文的周几
        return $weekdays[$englishDay]; // 转换为中文周几
    }
    
    /**
     * 订单详情信息
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail($order_id)
    {
        // 订单详情 
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']); 
        $model['goods'][0]['jiuzhen'] = DB("user_jiuzhen")->where("jiuzhen_id",$model['goods'][0]['jiuzhen_id'])->find();
        $model['goods'][0]['category'] = DB("category")->where("category_id",DB("goods")->where("goods_id",$model['goods'][0]['goods_id'])->find()['category_id'])->find();
        // $model['goods'][0]['jiuzhen'][0]['slot'] = $this->getTimePeriod($model['goods'][0]['jiuzhen_time']);
        $model['goods'][0]['slot'] = $this->getTimePeriod($model['goods'][0]['jiuzhen_time']);
        $model['goods'][0]['Weekday'] = $this->getWeekday($model['goods'][0]['jiuzhen_day']);
        $model['goods'][0]['mz_type'] = DB("goods")->where("goods_id", $model['goods'][0]['goods_id'])->find()['mz_type'];

        // 该订单是否允许申请售后
        $model['isAllowRefund'] = $model->isAllowRefund();
        // 如果已就诊也不允许退款
        if ($model->order_status['value'] == 30) {
            $model['isAllowRefund'] = false;
        }
        // 是否已评价
        $hasCommented = DB('goods_doctor_comment')
            ->where([
                'order_id' => $order_id,
                'user_id' => $this->user['user_id']
            ])
            ->count() > 0;

        $model['is_commented'] = $hasCommented;

        return $this->renderSuccess([
            'order' => $model,  // 订单详情
            'comment'=>DB("goods_doctor_comment")->where("order_id",$order_id)->find(), // 订单评论
            'setting' => [
                // 积分名称
                'points_name' => SettingModel::getPointsName(),
            ],
        ]);
    }
    public function getWeekday($date)
    {
        if (empty($date)) {
            return '';
        }
        // 周几映射表
        $weekdays = [
            'Sunday' => '周日',
            'Monday' => '周一',
            'Tuesday' => '周二',
            'Wednesday' => '周三',
            'Thursday' => '周四',
            'Friday' => '周五',
            'Saturday' => '周六',
        ];

        // 将日期转换为周几
        $dayOfWeek = date('l', strtotime($date));

        // 返回对应的中文表示
        return $weekdays[$dayOfWeek] ?? '未知';
    }
    public function getTimePeriod($timeRange) {
        if (empty($timeRange)) {
            return '未知时间段';
        }
        // 拆分时间段，取开始时间
        [$start, $end] = explode('-', $timeRange);
        $hour = (int)explode(':', $start)[0];
    
        if ($hour < 12) {
            return '上午';
        } elseif ($hour < 18) {
            return '下午';
        } else {
            return '夜间';
        }
    }
    /**
     * 获取物流信息
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function express($order_id)
    {
        // 订单信息
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if (!$order['express_no']) {
            return $this->renderError('没有物流信息');
        }
        // 获取物流信息
        /* @var \app\store\model\Express $model */
        $model = $order['express'];
        $express = $model->dynamic($model['express_name'], $model['express_code'], $order['express_no']);
        if ($express === false) {
            return $this->renderError($model->getError());
        }
        return $this->renderSuccess(compact('express'));
    }

    /**
     * 取消订单
     * @param $order_id
     * @return array
     * @throws \Exception
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function cancel($order_id)
    {
        // dump($order_id);die;
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if ($model->cancel($this->user)) {
            // 开始发送消息
            // 获取小程序配置
            $wxappId = "10001";
            $wxConfig = WxappModel::getWxappCache($wxappId);
            // 请求微信api执行发送
            $WxSubMsg = new WxSubMsg($wxConfig['app_id'], $wxConfig['app_secret']);
            $params = [
                'touser' => DB("user")->where("user_id", $model['user_id'])->find()['open_id'],
                'template_id' => 'E3w69uDbrXTpAIJ036bmDWPQzSrpAf2GAkxKD2rgXMI',
                'page' => '',
                'data' => [
                    'name1' => [
                        'value' => DB("user_jiuzhen")->where("jiuzhen_id", $model['goods'][0]['jiuzhen_id'])->find()['name'] ?: '默认姓名'
                    ],
                    'name6' => [
                        'value' => $model['goods'][0]['goods_name'] ?: '默认商品名称'
                    ],
                    'thing2' => [
                        'value' => DB("category")->where('category_id', DB("goods")->where('goods_id', $model['goods'][0]['goods_id'])->find()['category_id'])->find()['name'] ?: '默认分类'
                    ],
                    'date4' => [
                        'value' => $model['goods'][0]['jiuzhen_day'] ?: '无预约日期'
                    ],
                    'thing5' => [
                        'value' => "您好，您已取消预约挂号"
                    ],
                ],
            ];
            $WxSubMsg->sendTemplateMessage($params);
            // 发送消息结束
            return $this->renderSuccess($model->getError() ?: '订单取消成功');
        }
        return $this->renderError($model->getError() ?: '订单取消失败');
    }

    /**
     * 确认收货
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function receipt($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if ($model->receipt()) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }

    /**
     * 立即支付
     * @param int $order_id 订单id
     * @param int $payType 支付方式
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function pay($order_id, $payType = PayTypeEnum::WECHAT)
    {
        // 获取订单详情
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        // 订单支付事件
        if (!$model->onPay($payType)) {
            return $this->renderError($model->getError() ?: '订单支付失败');
        }
        // 构建微信支付请求
        $payment = $model->onOrderPayment($this->user, $model, $payType);
        // 支付状态提醒
        return $this->renderSuccess([
            'order_id' => $model['order_id'],   // 订单id
            'pay_type' => $payType,             // 支付方式
            'payment' => $payment               // 微信支付参数
        ], ['success' => '支付成功', 'error' => '订单未支付']);
    }

    /**
     * 获取订单核销二维码
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function extractQrcode($order_id)
    {
        // 订单详情
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        // 判断是否为待核销订单
        if (!$order->checkExtractOrder($order)) {
            return $this->renderError($order->getError());
        }
        $Qrcode = new ExtractQRcode(
            $this->wxapp_id,
            $this->user,
            $order_id,
            OrderTypeEnum::MASTER
        );
        return $this->renderSuccess([
            'qrcode' => $Qrcode->getImage(),
        ]);
    }

}
